'''python 表达式计算'''
import unittest
import tkinter as tk
import tkinter.messagebox as msbox
import pyperclip

from math import *
from lib.funcs import *

class calc_class:
    def __init__(self):
        pass

    def calculate(self, data):
        ans = eval(data)
        return ans


class GUI_calc:
    '''图形界面管理类-计算界面'''

    def __init__(self, father, sitting) -> None:
        '''初始化'''
        self.sitting = sitting["modules"]["calc"]
        self.window = father

        self.__init__component()

    def __init__component(self):
        '''初始化组件'''
        self._dat_outbox = tk.StringVar()

        self.btframe = frame(self.window)  # 两大框架
        self.boxframe = frame(self.window)

        self.comframe = frame(self.boxframe)

        self.inbox = entry(
            self.comframe, nameof="input_box", sitting=self.sitting)

        self.tip = label(
            self.comframe, nameof="tip_area", text=self.sitting['tip_area']['tip'], sitting=self.sitting)

        self.outbox = label(
            self.boxframe, text=self._dat_outbox,
            nameof="output_box", sitting=self.sitting)  # 设置输出框

        self.runit = button(
            self.btframe, command=self.__when_button_clicked,
            nameof="button", sitting=self.sitting)  # 设置运行按钮

        self.cpbutton = button(
            self.btframe, command=self.__copy_to_clipborad,
            nameof="copy_button", sitting=self.sitting)  # 设置拷贝到剪贴板按钮

        self.tip.pack(side=tk.LEFT)
        self.inbox.pack(side=tk.RIGHT)
        self.comframe.pack(side=tk.TOP)

        self.outbox.pack(side=tk.BOTTOM)
        self.boxframe.pack(side=tk.TOP)

        self.runit.pack(side=tk.RIGHT)
        self.cpbutton.pack(side=tk.LEFT)
        self.btframe.pack(side=tk.BOTTOM)

        self.func = calc_class()  # 全部加载

    def __when_button_clicked(self):
        '''处理按下按钮事件'''
        input_box_data = str(self.inbox.get())
        if len(input_box_data) == 0:
            msbox.showerror(title='Error!', message='未输入字符！')
        else:  # 是文字
            self.func_run()

    def func_run(self):
        '''进行eval表达式计算'''
        ans = "-E-"
        try:
            ans = self.func.calculate(str(self.inbox.get()))
        except Exception as w:
            msbox.showerror(title='Error!', message=f'表达式有误!\n{w}')
        self._dat_outbox.set(ans)

    def __copy_to_clipborad(self):
        '''复制到剪贴板'''
        pyperclip.copy(self._dat_outbox.get())
